package org.javaside.giveme.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.javaside.giveme.core.OAuthHolder;
import org.javaside.giveme.core.WeiboConfig;
import org.javaside.giveme.vo.GiveMeContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;

import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

import com.tencent.weibo.api.T_API;

/**
 * 微薄controller
 * 
 * @author xiaozhou
 *
 */
@Controller
@SessionAttributes(value={"ttRequestToken","ttAccessToken","requestToken","accessToken","user","gmctx"})
public class WeiBoController {
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private OAuthHolder oAuthHolder;
	@Autowired
	private WeiboConfig weiboConfig;
	
	@RequestMapping("/send")
	public String sendWeibo(@RequestParam(required=false) String content,
							HttpServletRequest request,
							WebRequest webRequest,
							Model model){
		AccessToken sinaAccessToken = (AccessToken)webRequest.getAttribute("accessToken", RequestAttributes.SCOPE_SESSION);
		com.tencent.weibo.beans.OAuth ttAccessToken = (com.tencent.weibo.beans.OAuth)webRequest.getAttribute("ttAccessToken", RequestAttributes.SCOPE_SESSION);
		//logger.info("ip:{}",request.getRemoteAddr());
		String status = "";
		if(StringUtils.isNotEmpty(content)){
			content = content.concat(" "+weiboConfig.getJavasideUrl());
			boolean sinaStatus = false;
			boolean ttSatuts = false;
			//发布新浪微薄
			if(sinaAccessToken!=null){
				Weibo weibo = new Weibo();
				weibo.setToken(sinaAccessToken);
				try {
					weibo.updateStatus(content);
					sinaStatus =true;
				} catch (WeiboException e) {
					logger.error("新浪微薄发布失败!",e);
					status = "&weiboStatus=sinaError";
				}
			}
			
			//发布腾讯微薄
			if(ttAccessToken!=null){
				T_API tApi = new T_API();
				try {
					tApi.add(ttAccessToken, "xml", content, getXRealIP(request));
					ttSatuts = true;
				} catch (Exception e) {
					logger.error("腾讯微薄发布失败!",e);
					status = "&weiboStatus=ttError";
				}
			}
			
			if(sinaStatus || ttSatuts){
				status = status + "&status=success";
			}
		}
		return "redirect:/myHome?"+status;
	}
	
	@RequestMapping("/myHome")
	public String userHome(
							@RequestParam(required=false)String status,
							@RequestParam(required=false)String weiboStatus,
							Model model){
		model.addAttribute("status", status);
		model.addAttribute("weiboStatus", weiboStatus);
		return "myHome";
	}
	
	@RequestMapping("/sina_callback")
	public String sinaCallBack(@RequestParam(required=false) String oauth_verifier,
						   @RequestParam(required=false) String oauth_token,
						   WebRequest webRequest,
						   Model model){
		//验证是否已经登录，避免重复想新浪发登录请求。
		RequestToken requestToken = (RequestToken)webRequest.getAttribute("requestToken", RequestAttributes.SCOPE_SESSION);
		AccessToken accessToken = (AccessToken)webRequest.getAttribute("accessToken", RequestAttributes.SCOPE_SESSION);
		GiveMeContext gmctx = (GiveMeContext)webRequest.getAttribute("gmctx", RequestAttributes.SCOPE_SESSION);
		
		if(accessToken==null && requestToken!=null){
			try {
				accessToken = oAuthHolder.requstAccessToken(requestToken, oauth_verifier);
				long userId = accessToken.getUserId();
				Weibo weibo = new Weibo();
				weibo.setToken(accessToken);
				User user = weibo.showUser(String.valueOf(userId));
				//logger.debug(ToStringBuilder.reflectionToString(user));
				
				gmctx = gmctx==null?new GiveMeContext():gmctx;
				gmctx.setProImgUrl(user.getProfileImageURL().toString());
				model.addAttribute("user",user);
				model.addAttribute("accessToken", accessToken);
				model.addAttribute("gmctx", gmctx);
			} catch (WeiboException e) {
				logger.error("微薄登录失败!",e);
				return "redirect:/?status=nologin";
			}
		}
		return "redirect:/myHome";
	}
	
	@RequestMapping("/tt_callback")
	public String ttCallBack(@RequestParam(required=false) String oauth_verifier,
						   @RequestParam(required=false) String oauth_token,
						   WebRequest webRequest,
						   Model model){
		//验证是否已经登录，避免重复想新浪发登录请求。
		com.tencent.weibo.beans.OAuth requestToken = (com.tencent.weibo.beans.OAuth)webRequest.getAttribute("ttRequestToken", RequestAttributes.SCOPE_SESSION);
		com.tencent.weibo.beans.OAuth accessToken = (com.tencent.weibo.beans.OAuth)webRequest.getAttribute("ttAccessToken", RequestAttributes.SCOPE_SESSION);
		GiveMeContext gmctx = (GiveMeContext)webRequest.getAttribute("gmctx", RequestAttributes.SCOPE_SESSION);
		
		if(accessToken==null && requestToken!=null){
			try {
				accessToken = oAuthHolder.ttAcessToken(requestToken, oauth_verifier);
				if (accessToken.getStatus() == 2) {
					logger.error("腾讯微薄登录失败!");
					return "redirect:/?status=ttLoginError";
				}
				
				gmctx = gmctx==null?new GiveMeContext():gmctx;
				model.addAttribute("ttAccessToken", accessToken);
				model.addAttribute("gmctx", gmctx);
			} catch (Exception e) {
				logger.error("腾讯微薄登录失败!",e);
				return "redirect:/?status=ttLoginError";
			}
		}
		return "redirect:/myHome";
	}
	
	
	/**
	 * 新浪登录验证
	 * @param webRequest
	 * @param model
	 * @return
	 */
	@RequestMapping("/sina_auth")
	public String sinaAuth(WebRequest webRequest,Model model){
		//验证是否已经登录，避免重复想新浪发登录请求。
		AccessToken accessToken = (AccessToken)webRequest.getAttribute("accessToken", RequestAttributes.SCOPE_SESSION);
		if(accessToken!=null) return "redirect:/myHome";
		
		RequestToken requestToken = null;
		try {
			requestToken = oAuthHolder.requestToken();
			model.addAttribute("requestToken", requestToken);
		} catch (WeiboException e) {
			logger.error("新浪微薄获取RequestToken错误。", e);
		}
		if(requestToken == null)return "redirect:/?status=nologin";
		return "redirect:"+requestToken.getAuthenticationURL();
	}
	
	/**
	 * 腾讯微薄认证
	 * @param webrRequest
	 * @param model
	 * @return
	 */
	@RequestMapping("/tt_auth")
	public String ttAuth(WebRequest webrRequest,Model model){
		String url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token=";
		// 获取request token
		try {
			com.tencent.weibo.beans.OAuth oauth = oAuthHolder.ttRequestToken();
			if (oauth.getStatus() == 1) {
				return "redirect:/?status=ttLoginError";
			}
			String oauth_token = oauth.getOauth_token();
			url = url + oauth_token;
			model.addAttribute("ttRequestToken", oauth);
		} catch (Exception e) {
			logger.error("腾讯微薄获取RequestToken失败.",e);
		}
		return "redirect:"+url;
	}
	
	@RequestMapping("/logout")
	public String logout(WebRequest webRequest,SessionStatus status){
		AccessToken accessToken = (AccessToken)webRequest.getAttribute("accessToken", RequestAttributes.SCOPE_SESSION);
		if(accessToken!=null){
			Weibo weibo = new Weibo();
			weibo.setToken(accessToken);
			try {
				weibo.endSession();
			} catch (WeiboException e) {
				logger.error("退出登录异常.",e);
			}
		}
		status.setComplete();
		return "redirect:/";
	}
	
	/**
	 * 获取代理ip
	 * @param req
	 * @return
	 */
	public static String getXRealIP(HttpServletRequest req){
		String ip = req.getHeader("X-Real-IP");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = req.getRemoteAddr();
		}
		
		return ip;
	}
}
